import apiRequest from '@/libs/api.request'
import _ from 'lodash';
import { Message } from 'element-ui';

// 菜单设置
function getTreeMenuData(arr, parentId) {
  let resultArr = []
  for (var i = 0; i < arr.length; i++) {
    if (parentId == arr[i].parentid) {
      arr[i].children = getTreeMenuData(arr, arr[i].id)
      resultArr.push(arr[i])
      resultArr.sort((a, b) => {
        return Number(a.sortNo) - Number(b.sortNo)
      })
    }
  }
  return resultArr
}

let breadcrumb = localStorage.getItem('breadcrumb')
if (breadcrumb) {
  breadcrumb = JSON.parse(breadcrumb)
} else {
  breadcrumb = []
}
let headTag = localStorage.getItem('headTag')
if (headTag) {
  headTag = JSON.parse(headTag)
} else {
  headTag = []
}
export default {
  state: {
    token: '',
    isDarkTheme: false,
    userInfo: {},  // 用户信息
    treeMenuArr: [],// 菜单
    searchValue: '',// 全局搜索
    breadcrumb: breadcrumb, // 面包屑
    headTag: headTag //头部logo后面的文字内容
    // token: ''
  },
  getters: {
    getTreeMenuArr: (state) => {
      return state.treeMenuArr
    },
    getUserInfo: (state) => {
      return state.userInfo
    },
    getBreadcrumb: (state) => {
      return state.breadcrumb
    },
    getSearchValue: (state) => {
      return state.searchValue
    },
    getisDarkTheme: (state) => {
      return state.isDarkTheme
    },
    getHeadTag: (state) => {
      return state.headTag
    },
  },
  mutations: {
    setTreeMenuArr(state, val) {
      state.treeMenuArr = val
    },
    setisDarkTheme(state, val) {
      state.isDarkTheme = val
    },
    setUserInfo(state, val) {
      state.userInfo = val
    },
    setToken(state, val) {
      state.token = val
    },
    setBreadcrumb: (state, val) => {
      localStorage.setItem('breadcrumb', JSON.stringify(val))
      state.breadcrumb = val
    },
    setHeadTag: (state, val) => {
      localStorage.setItem('headTag', JSON.stringify(val))
      state.headTag = val
    },
    setSearchValue(state, val) {
      state.searchValue = val
    },
    // setToken(state, val) {
    //   let token = localStorage.getItem('TOKEN_KEY')
    //   state.token = val || token
    // },

  },
  actions: {
    geUntLoginMenus({ commit }) {
      return new Promise((resolve, reject) => {
        apiRequest.axios.request({
          url: "5100/login/menus",
          method: "get",
        })
          .then(function (res) {
            let arr = _.get(res, 'data.user.menus', []);
            if (!arr) arr = []
            let result = getTreeMenuData(arr, -1)
            // 排序
            result.sort((a, b) => {
              return a.sortNo - b.sortNo
            })
            commit('setTreeMenuArr', result)
            commit('setUserInfo', res.data.user)
            // commit('setisDarkTheme', res.data.user.id == '577' ? true : false)
            resolve(res)

          })
          .catch(function (error) {
            commit('setTreeMenuArr', [])
            commit('setUserInfo', {})
            commit('setisDarkTheme', false)
            localStorage.removeItem('TOKEN_KEY')
            reject(error)
          });
      })
    },
    getUserInfo({ commit }) {
      let token = localStorage.getItem('TOKEN_KEY')
      let domain = window.location.hostname;
      let _token = window.location.hash.split("&")[2];
      if (token == undefined && _token != undefined) {
        let token_1 = _token.split("=")[1];
        if (token_1 != null) {
          token = token_1;
        }
      }
      return new Promise((resolve, reject) => {
        apiRequest.axios.request({
          url: "5000/oauth/userinfo",
          method: "post",
          params: {
            access_token: token || '1221af48-64b8-4970-9fa7-6f58cd82c2b8',
            domain: domain
          }
        })
          .then(function (res) {
            let arr = _.get(res, 'data.user.menus', []);
            if (!arr) arr = []
            let result = getTreeMenuData(arr, -1)
            // 排序
            result.sort((a, b) => {
              return a.sortNo - b.sortNo
            })
            commit('setTreeMenuArr', result)
            commit('setUserInfo', res.data.user)
            // commit('setisDarkTheme', res.data.user.id == '577' ? true : false)
            resolve(res)
          })
          .catch(function (error) {
            commit('setTreeMenuArr', [])
            commit('setUserInfo', {})
            commit('setisDarkTheme', false)
            localStorage.removeItem('TOKEN_KEY')
            reject(error)
            console.log(error, '----------------error登录失败-------');
          });
      })
    },
    getIpAddress() {
      var old_token = localStorage.getItem('TOKEN_KEY')
      if (old_token == null) {
        old_token = "1"
      }
      let self = this;
      return new Promise((resolve, reject) => {
        $.getJSON("https://v4v6.ipv6-test.com/json/widgetdata.php?callback=?", function (result) {

        }).then(function (result) {
          resolve(result)
        }).catch(function (error) {
          reject(error)
        })
      })
    },
    getTokenByIp({ commit }) {
      var old_token = localStorage.getItem('TOKEN_KEY')
      if (old_token == null) {
        old_token = "1221af48-64b8-4970-9fa7-6f58cd82c2b8"
      }
      return new Promise((resolve, reject) => {

        apiRequest.axios.request({
          url: "5000/oauth/get/token",
          method: "post",
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
          params: {
            access_token: old_token
          }
        }).then(res => {
          let token = res.data.access_token
          if (!old_token || old_token != token) {
            localStorage.setItem('TOKEN_KEY', token)
          }
          resolve(res)
        }).catch((error) => {
          reject(error)
          localStorage.clear()
        })
      })

    },
    getIpFreeToken() {
      let self = this;
      let ipv6 = localStorage.getItem('IP_ADS')
      let domain = window.location.hostname;
      if (ipv6 == null) {
        ipv6 = ""
      }
      return new Promise((resolve, reject) => {
        apiRequest.axios.request({
          url: "5000/authentication/ipfree",
          method: "post",
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'client-id': 'webApp',
            'client-secret': 'webApp',
          },
          params: {
            ipv6: ipv6,
            domain: domain
          }
        }).then(res => {
          let old_token = localStorage.getItem('TOKEN_KEY')
          let token = res.data.access_token
          if (!old_token || old_token != token) {
            localStorage.setItem('TOKEN_KEY', token)
          }
          resolve(res)
        }).catch((error) => {
          reject(error)
          // Message({
          //   message: "此账号已到期",
          //   type: 'error'
          // })
        })
      })
    },

  },

}
